package desktop.playerguide.multichoiceswin;

import java.util.ArrayList;

import pulpcore.animation.Timeline;
import pulpcore.animation.event.TimelineEvent;
import pulpcore.scene.Scene2D;
import pulpcore.sprite.Group;
import pulpcore.sprite.StretchableSprite;
import pulpcore.Input;
import pulpcore.Stage;

public class ChoiceForm extends Group {

	private Group form;
	private boolean isNeedBack = false;
	private ArrayList<Item> myItems = new ArrayList<Item>();
	ItemFactory itemFactory = ItemFactory.getItemFactory();
	StretchableSprite background = new StretchableSprite("border.9.png", 0, 0,
			480, 320);
	
	public ChoiceForm(String title) {
		form = new Group(Stage.getWidth() / 2, Stage.getHeight() / 2, 480, 320);
		form.setAnchor(0.5, 0.5);
		background.alpha.set(80);
		form.add(background);
		myItems.addAll(itemFactory.getItemList(title));

		for (Item item : myItems) {
			form.add(item);
		}

		((Scene2D) Stage.getScene()).addLayer(form);
	}

	@Override
	public void update(int elapsedTime) {
		super.update(elapsedTime);
		this.keyPressCheck(elapsedTime);
		if (isNeedBack) {
			this.removeEffect();
		}
	}

	private void removeEffect() {
		Timeline t = new Timeline();
		t.move(form, form.x.get(), form.y.get(), Stage.getWidth(), Stage
				.getHeight(), 400);
		t.scaleTo(form, 0, 0, 400);
		t.animateTo(form.alpha, 0, 400);
		((Scene2D) Stage.getScene()).addTimeline(t);
		t.after(400).addEvent(new TimelineEvent(2) {
			public void run() {
				// Code to execute after the delay
				((Scene2D) Stage.getScene()).reload();
			}
		});
		((Scene2D) Stage.getScene()).addTimeline(t);
	}

	private void keyPressCheck(int elapsedTime) {
		if (Input.isDown(Input.KEY_ESCAPE)) {
			isNeedBack = true;
		}
		for (final Item item : myItems) {
			if (item.isMouseOver()) {
				int blurGoal = isMouseOver() ? 10 : 0;
				if (!item.getBlur().radius.isAnimating()
						&& item.getBlur().radius.get() != blurGoal) {
					int dur = 100 + blurGoal * 20;
					item.getBlur().radius.animateTo(blurGoal, dur);
				}
			}
			if (item.isMouseDown()) {
				Timeline clickedTimeLine = new Timeline();
				clickedTimeLine.scaleTo(item, item.getViewX(), item.getViewX()*1.3, 200);
				clickedTimeLine.scaleTo(item, item.getViewY(), item.getViewY()*1.3, 200);
				clickedTimeLine.animateTo(item.alpha, 120, 200);
				((Scene2D)Stage.getScene()).addTimeline(clickedTimeLine);
				clickedTimeLine.at(200).animateTo(item.alpha,0,300);
				clickedTimeLine.at(200).scaleTo(item, item.getViewX()*1.3, 0, 300);
				clickedTimeLine.at(200).scaleTo(item, item.getViewY()*1.3, 0, 300);
				clickedTimeLine.at(200).animateTo(item.alpha, 0, 200);
				((Scene2D)Stage.getScene()).addTimeline(clickedTimeLine);
				clickedTimeLine.after(200).addEvent(new TimelineEvent(12){
					@Override
					public void run() {
						item.do_action(0);
					}					
				});
			
			}
		}
	}
}
